package com.rokyinfo.generator;


import org.apache.commons.lang.StringUtils;

import java.util.Random;

/**
 * Created by yuanzhijian on 2017/2/4.
 */
public class SNGenerator {

    public enum UEType {
        CCU, DCU, KEY
    }

    /**
     * 生成SN号
     * @param type 生产类型
     * @param lastUESn 最后生成的SN号
     * @param i
     * @return
     */
    public static String generateUESn(UEType type, String lastUESn, int i) throws Exception {

        if ( StringUtils.isEmpty(lastUESn) || lastUESn.length() < 10){
            throw new IllegalArgumentException("最后生成的SN号非法");
        }

        String ueSnHexIncrementNum = String.valueOf(lastUESn.charAt(9))
                + String.valueOf(lastUESn.charAt(7))
                + String.valueOf(lastUESn.charAt(6))
                + String.valueOf(lastUESn.charAt(4));

        Integer baseIncrement = Integer.parseInt(ueSnHexIncrementNum, 16);

        String serialNum = lastUESn.substring(1, 4);

        if (baseIncrement + i + 1 >= 0xffff) {

            baseIncrement = 0;
            serialNum = getMappingCode(serialNum);
        }

        String tempStr = Integer.toHexString(baseIncrement + i + 1);
        while (tempStr.length() < 4) {
            tempStr = "0" + tempStr;
        }

        StringBuffer sb = new StringBuffer(tempStr);
        sb = sb.reverse();
        String randomStr = getRandomString(2);
        sb.insert(1, randomStr.charAt(0));
        sb.insert(4, randomStr.charAt(1));

        if (type == UEType.CCU) {
            return "B" + serialNum + sb.toString().toUpperCase();
        } else if (type == UEType.KEY) {
            return "K" + serialNum + sb.toString().toUpperCase();
        } else if (type == UEType.DCU) {
            return "G" + serialNum + sb.toString().toUpperCase();
        }

        return null;
    }

    private static String getMappingCode(String oldMappingCode) {

        char ch1 = oldMappingCode.charAt(2);
        char ch2 = oldMappingCode.charAt(1);
        char ch3 = oldMappingCode.charAt(0);

        ch1 = incrementChar(ch1);
        if (ch1 == '0') {

            ch2 = incrementChar(ch2);

            if (ch2 == '0') {
                ch3 = incrementChar(ch3);
            }
        }

        return String.valueOf(ch3) + String.valueOf(ch2) + String.valueOf(ch1);
    }

    private static char incrementChar(char ch) {

        String base = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ";

        return base.indexOf(ch) == (base.length() - 1) ? base.charAt(0) : base
                .charAt(base.indexOf(ch) + 1);
    }

    private static String getRandomString(int length) {
        String base = "abcdefghjklmnpqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

}
